package leetcode25

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

// 缩放为n 组的反转 ,每次传入前置pre 和后继 next node进行拼接
// 记得判空
// 特殊 k == 1 就是原队列
func reverseKGroup(head *ListNode, k int) *ListNode {
	if k <= 1 {
		return head
	}
	hair := &ListNode{
		Next: head,
	}

	var (
		pre  *ListNode
		tail *ListNode
	)
	tail = hair.Next
	pre = hair

	for {
		for i := 0; i < k-1; i++ {
			if tail == nil {
				return hair.Next
			}
			tail = tail.Next
		}
		if tail == nil {
			return hair.Next
		}
		temp := tail.Next
		temp1 := pre.Next
		reverseList(pre, pre.Next, tail, tail.Next)
		if temp == nil {
			return hair.Next
		}
		pre = temp1
		tail = temp
	}
}

func reverseList(listPre, head, tail, tailNext *ListNode) {
	cur := head
	var pre *ListNode
	for cur != tailNext {
		next := cur.Next
		cur.Next = pre
		pre = cur
		cur = next
	}
	listPre.Next = pre
	head.Next = tailNext
	return
}

func makeList(input []int) *ListNode {
	var (
		res *ListNode
		cur *ListNode
	)
	if len(input) == 0 {
		return nil
	}
	res = &ListNode{}
	cur = res
	for i, item := range input {
		cur.Val = item
		if i != len(input)-1 {
			cur.Next = &ListNode{}
			cur = cur.Next
		}
	}
	return res
}

func PrintList(head *ListNode) {
	for head != nil {
		fmt.Print(head.Val)
		head = head.Next
	}
}

func toArr(head *ListNode) (res []int) {
	res = make([]int, 0)
	for head != nil {
		res = append(res, head.Val)
		head = head.Next
	}
	return
}
